//
//  YZDailyWorkListVC.m
//  VET
//
//  Created by Lam BG on 2018/7/10.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZDailyWorkListVC.h"

// view
#import "YZEmptyView.h"
#import "YZDailyWorkCell.h"

// model
#import "YZDailyWorkItem.h"
#import "YZDailyWorkModel.h"

// api
#import "YZWorkbenchAPI.h"

// other
#import "YZJsonFileLoader.h"

// 第三方
#import "MJRefresh.h"
#import "MJExtension.h"

// category
#import "UIColor+Category.h"
#import "NSString+DisplayTime.h"

@interface YZDailyWorkListVC () <UITableViewDelegate, UITableViewDataSource, DailyWorkCheckHandleDelegate>

// 显示空的时候的视图
@property (weak, nonatomic) YZEmptyView *emptyView;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) YZWorkbenchAPI *dailyWorkAPI;

@property (nonatomic, strong) NSMutableArray *data;  // 数据

@property (nonatomic, assign) NSInteger currentPage; // 请求数据页

@property (nonatomic, assign) NSInteger total;       // 总数

@end

@implementation YZDailyWorkListVC

#pragma mark - life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self setupTableView];
    [self setupRefresh];
    
    // 监听页面数据更新通知
    @weakify(self)
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:kUndoRefreshNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * notification) {
        
        @strongify(self)
        if (notification.object) {
            if ((DWItemType)[notification.object intValue] == self.dailyWorkItem.itemType) {
                
                [self.tableView.mj_header beginRefreshing];
            }
        } else {
            
            [self.tableView.mj_header beginRefreshing];
        }
        
    }];
}

#pragma mark - setup function

- (void)setupTableView {
    
    // tableView 设置
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;             // 将原点移动到navigationBar下面去了
    self.tableView.estimatedRowHeight = 37.0;                 // 估计cell的高度
    self.tableView.rowHeight = UITableViewAutomaticDimension; // 行高自适应
    self.tableView.tableFooterView = [UIView new];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    
    // 注册 cell
    [self.tableView registerNib:[UINib nibWithNibName:@"YZDailyWorkCell" bundle:nil] forCellReuseIdentifier:kDailyWorkCellID];
}

- (void)setupRefresh {
    
    // 设置刷新控件
    @weakify(self)
    
    // header
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        @strongify(self)
        [self loadNewData];
    }];
    self.tableView.mj_header = header;
    // 请求数据
    [self.tableView.mj_header beginRefreshing];
    
    
    
    // footer
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        @strongify(self)
        [self loadMoreData];
    }];
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.hidden = YES;
}

#pragma mark - load function

// 获取数据
- (void)loadNewData {
    
    @weakify(self)
    // 开始时间戳
    self.currentPage = 0;
    [self.dailyWorkAPI addParams:@{@"index" : @(0)}];
    [[self.dailyWorkAPI getRequest] subscribeNext:^(NSDictionary *data) {
        
        @strongify(self)
        NSArray *list = data[@"list"];
        if (kNullable(data[@"total"])) self.total = [data[@"total"] integerValue];
        
        // 清除内存数据
        [self.data removeAllObjects];
        
        if (list.count) {
            
            // 生成数据
            [self.data addObjectsFromArray:[YZDailyWorkModel mj_objectArrayWithKeyValuesArray:list]];
        }
        [self loadNewComplete];
        
    } error:^(NSError * _Nullable error) {
        
        @strongify(self)
        [self loadNewComplete];
        
    }];
}

- (void)loadMoreData {
    
    @weakify(self)
    [self.dailyWorkAPI addParams:@{@"index" : @(++self.currentPage)}];
    [[self.dailyWorkAPI getRequest] subscribeNext:^(NSDictionary *data) {
        
        @strongify(self)
        NSArray *list = data[@"list"];
        if (kNullable(data[@"total"])) self.total = [data[@"total"] integerValue];
        
        if (list.count) {
            
            // 生成数据
            [self.data addObjectsFromArray:[YZDailyWorkModel mj_objectArrayWithKeyValuesArray:list]];
            [self loadMoreComplete];
            
        } else {
            
            // 没有更多数据了
            --self.currentPage;
            [self loadMoreCompleteWithNoMoreData];
        }
        
    } error:^(NSError * _Nullable error) {
        
        @strongify(self)
        [self loadMoreComplete];
        
    }];
}

- (void)loadNewComplete {
    
    // 判断 footer 状态
    if (self.data.count < self.total) {
        
        [self.tableView.mj_footer endRefreshing];
    } else {
        
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    
    [self.tableView.mj_header endRefreshing];
    [self loadDataComplete];
}

- (void)loadMoreComplete {
    
    // 判断 footer 状态
    if (self.data.count < self.total) {
        
        [self.tableView.mj_footer endRefreshing];
    } else {
        
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    
    [self.tableView.mj_footer endRefreshing];
    [self loadDataComplete];
}

- (void)loadMoreCompleteWithNoMoreData {
    
    [self.tableView.mj_footer endRefreshingWithNoMoreData];
    [self loadDataComplete];
}

- (void)loadDataComplete {
    
    [self.tableView reloadData];
    
    // 加载完成后 判断数据
    BOOL isDataExist = self.data.count != 0;
    self.emptyView.hidden = isDataExist;
    self.tableView.mj_footer.hidden = !isDataExist;
}

#pragma mark - handle daily work delegate

- (void)handleDailyWorkChecked:(NSIndexPath*)indexPath withError:(NSError*)error {
    
    if (error == nil) {
        
        // 成功
        [self.data removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
        [self loadDataComplete];
    }
}

#pragma mark - table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 12;
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    
    view.tintColor = [UIColor clearColor];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YZDailyWorkModel *model = self.data[indexPath.row];
    YZDailyWorkCell *cell = [tableView dequeueReusableCellWithIdentifier:kDailyWorkCellID forIndexPath:indexPath];
    
    // 设置数据
    model.itemType = self.dailyWorkItem.itemType;
    cell.model = model;
    cell.indexPath = indexPath;
    cell.delegate = self;
    
    return cell;
}

#pragma mark - getter

- (YZEmptyView *)emptyView {
    
    if (_emptyView == nil) {
        
        _emptyView = [[[NSBundle mainBundle] loadNibNamed:@"YZEmptyView" owner:nil options:nil] firstObject];
        _emptyView.frame = self.view.bounds;
        
        [self.view addSubview:_emptyView];
    }
    
    return _emptyView;
}

- (YZWorkbenchAPI *)dailyWorkAPI {
    
    if (_dailyWorkAPI == nil) {
        
        _dailyWorkAPI = [YZWorkbenchAPI initWithItemType:self.dailyWorkItem.itemType];
    }
    
    return _dailyWorkAPI;
}

- (NSMutableArray *)data {
    
    if (_data == nil) {
        
        _data = [NSMutableArray array];
    }
    
    return _data;
}


@end















